// @ts-check
import React, { Component } from 'react'
import createSocket from '../helpers/createSocket'
import GameContainer from './Game/Game'
import Info from './Info/Info'

class Root extends Component {
  state = {
    connected: false,
    serverUp: null,
    path: window.location.pathname.substr(1)
  }

  componentDidMount() {
    createSocket()
      .then(socket => {
        this.socket = socket
        this.setState({
          connected: true,
          serverUp: true
        })
      })
      .catch(() => {
        this.socket = {
          on: () => { },
          emit: () => { },
          fake: true
        }
        this.setState({
          connected: false,
          serverUp: false
        })
      })
  }

  render() {
    const { connected, serverUp } = this.state

    if (!connected && serverUp === null) {
      return (
        <div>Connecting...</div>
      )
    }

    return (
      <div className="root">
        {
          serverUp && <Info socket={this.socket} />
        }
        <GameContainer socket={this.socket} />
      </div>
    )
  }
}

export default Root
